package com.walle.concurrenttest.pattern.readwritelock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhangjiapeng
 * @Package com.walle.concurrenttest.pattern.readwritelock
 * @Description: ${todo}
 * @date 2019/2/20 13:53
 */
public class ReadWriteLock {


    private int readingReaders = 0;
    private int waitingWrites = 0;
    private int writingWriters = 0;
    private boolean preferWriter = true;

    public synchronized void readLock() throws InterruptedException {
        while (waitingWrites > 0 || writingWriters > 0){
            this.wait();
        }
        readingReaders++;
    }

    public synchronized void readUnLock(){
        readingReaders--;
        preferWriter = true;
        this.notifyAll();
    }

    public synchronized void writeLock() throws InterruptedException {
        waitingWrites++;
        try {
            while (readingReaders > 0 || writingWriters >0){
                this.wait();
            }
        } finally {
            waitingWrites--;
        }
        writingWriters++;
    }

    public synchronized void writeUnLock(){
        writingWriters--;
        preferWriter = false;
        this.notifyAll();
    }

}
